#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#include "MSTK.h"


#ifdef __cplusplus
extern "C" {
#endif
  /* This function partition the mesh into submeshes,
     GEntID and GEntDim will be retained in submesh for
     vertex and faces.
     
     For parallel code: also assigns global id, master 
     partition id on both global and sub meshes.
     
     No PType is assigned, call PMESH_BuildPType().

     Caller function should allocate memory for submeshes: 
     Mesh_ptr *submeshes = (Mesh_ptr*) MSTK_malloc(num*sizeof(Mesh_ptr);
  */

int MESH_Partition(Mesh_ptr mesh, Mesh_ptr *submeshes, int num) {
  int nf, nr, idx;
  MVertex_ptr global_mv;
  MEdge_ptr global_me;
  MFace_ptr global_mf;
  MRegion_ptr global_mr;
  /* basic mesh information */
  RepType rtype = MESH_RepType(mesh);
  nf = MESH_Num_Faces(mesh);
  nr = MESH_Num_Regions(mesh);
  /* assign global ID equal to ID for global mesh*/
  idx = 0;
  while((global_mv = MESH_Next_Vertex(mesh,&idx)))
    MV_Set_GlobalID(global_mv,MV_ID(global_mv));
  /* if there is edge */
  idx = 0;
  if (rtype < R1 || rtype > R4)
    while((global_me = MESH_Next_Edge(mesh,&idx)))
      ME_Set_GlobalID(global_me,ME_ID(global_me));

  idx = 0;
  while((global_mf = MESH_Next_Face(mesh,&idx)))
    MF_Set_GlobalID(global_mf,MF_ID(global_mf));
  idx = 0;  
  if(nr)
    while((global_mr = MESH_Next_Region(mesh,&idx)))
      MR_Set_GlobalID(global_mr,MR_ID(global_mr));

  if (nr) 
    MESH_Vol_Partition(mesh,submeshes,num);
  else if(nf) 
    MESH_Surf_Partition(mesh,submeshes,num);
  else {
    fprintf(stdout,"\nThis is not a valid mstk file for partition\n");
    exit(-1);
  }
  return 1;
}
  
#ifdef __cplusplus
}
#endif

